package com.lhkj.ct.meta.modules.warning.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lhkj.ct.base.enums.DeleteStatus;
import com.lhkj.ct.base.model.dto.PageQuery;
import com.lhkj.ct.base.mybatis.core.metadata.SqlOrder;
import com.lhkj.ct.base.mybatis.extension.service.impl.IServiceImpl;
import com.lhkj.ct.base.utils.AviatorUtil;
import com.lhkj.ct.base.utils.ShiroUtil;
import com.lhkj.ct.meta.modules.gauge.mapper.ScaleWarnSettingMapper;
import com.lhkj.ct.meta.modules.gauge.model.entity.TblScaleWarnSetting;
import com.lhkj.ct.meta.modules.psychology.mapper.ScaleReportMapper;
import com.lhkj.ct.meta.modules.psychology.model.bo.DimensionBo;
import com.lhkj.ct.meta.modules.psychology.model.bo.SubmitGaugeBo;
import com.lhkj.ct.meta.modules.psychology.model.entity.TblScaleReport;
import com.lhkj.ct.meta.modules.warning.mapper.ScaleWarnRecordMapper;
import com.lhkj.ct.meta.modules.warning.model.entity.TblScaleWarnRecord;
import com.lhkj.ct.meta.modules.warning.service.ScaleWarnRecordService;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 预警记录 服务实现类
 * </p>
 *
 * @author jobob
 * @since 2023-10-17
 */
@Service
public class ScaleWarnRecordServiceImpl extends IServiceImpl<ScaleWarnRecordMapper, TblScaleWarnRecord> implements ScaleWarnRecordService {

    private final Logger logger = LoggerFactory.getLogger(ScaleWarnRecordServiceImpl.class);

    @Resource
    private ScaleWarnSettingMapper warnSettingMapper;

    @Resource
    private ScaleReportMapper reportMapper;

    @Override
    public IPage<TblScaleWarnRecord> selectWarnPage(TblScaleWarnRecord record, PageQuery pageQuery) {
        Page<TblScaleWarnRecord> page = generatePage(pageQuery, SqlOrder.asc(TblScaleWarnRecord::getStatus, "t"), SqlOrder.desc(TblScaleWarnRecord::getWarnTime, "t"));
        return getBaseMapper().selectWarnPage(page, record, pageQuery);
    }

    public void generateWarnRecord(List<DimensionBo> dimensions, SubmitGaugeBo.Patient patient, String scaleId, String reportId) {
        boolean handle = false;
        for (DimensionBo dimension : dimensions) {
            if (BooleanUtils.toBooleanDefaultIfNull(dimension.getWarn(), false)) {
                continue;
            }
            // step 1.查询预警设置
            List<TblScaleWarnSetting> warns = warnSettingMapper.selectList(new LambdaQueryWrapper<TblScaleWarnSetting>()
                    .eq(TblScaleWarnSetting::getDimId, dimension.getId()).eq(TblScaleWarnSetting::getDelFlag, DeleteStatus.NORMAL));
            Map<String, Object> params = new HashMap<>();
            params.put("age", patient.getAge());
            params.put("Score", dimension.getRealScore());
            // step 2.过滤符合条件的预警设置
            List<TblScaleWarnSetting> warnSetDtoList = warns.stream()
                    .filter(w -> ((StringUtils.isBlank(w.yjAgeExp()) || (Boolean) AviatorUtil.compute(params, w.yjAgeExp()))
                            && (StringUtils.isBlank(w.getSuitSex()) || w.getSuitSex().equals(patient.getSex()))
                            && (StringUtils.isBlank(w.yjScoreExp()) || (Boolean) AviatorUtil.compute(params, w.yjScoreExp())))).collect(Collectors.toList());
            // step 3.判断是否生成预警记录
            if (CollectionUtil.isNotEmpty(warnSetDtoList)) {
                if (!handle) {
                    handle = true;
                    reportMapper.updateById(new TblScaleReport() {{
                        setDangerous(true);
                        setId(reportId);
                    }});
                }
                for (TblScaleWarnSetting warnSetDto : warnSetDtoList) {
                    TblScaleWarnRecord warnRecord = TblScaleWarnRecord.builder()
                            .scaleId(scaleId)
                            .patId(patient.getId())
                            .patName(patient.getName())
                            .patSex(patient.getSex())
                            .patAge(patient.getAge())
                            .rId(reportId)
                            .dimId(dimension.getId())
                            .dimName(dimension.getDimName())
                            .warnId(warnSetDto.getId())
                            .warningLevel(warnSetDto.getWarnLevel())
                            .warnTime(LocalDateTime.now())
                            .status(0).build();
                    try {
                        getBaseMapper().insert(warnRecord);
                    } catch (Exception e) {
                        logger.error("预警记录生成失败：{}", ExceptionUtils.getMessage(e));
                    }
                }
            }
        }
    }

    @Override
    public int handle(Collection<?> ids) {
        return getBaseMapper().update(new LambdaUpdateWrapper<TblScaleWarnRecord>()
                .set(TblScaleWarnRecord::getStatus, 1)
                .set(TblScaleWarnRecord::getProcessor, ShiroUtil.getAuthUserInfo().getUserId())
                .set(TblScaleWarnRecord::getProcessingTime, LocalDateTime.now())
                .eq(TblScaleWarnRecord::getStatus, 0)
                .in(TblScaleWarnRecord::getId, ids)
        );
    }

}
